package com.sgb.kjwl.viewmodel.pick;

import android.content.Intent;
import android.text.TextUtils;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.TenderListEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.pick.ReportActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.fragment.pick.PickHallBidingFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.dialog.DialogHelper;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PickHallBidingModel extends BaseViewModel {

    private HomeRepertory repertory;
    private PickHallBidingFragment fragment;
    private HashMap map;
    private int page;

    public PickHallBidingModel(PickHallBidingFragment fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    public void getList(String cityNo, String typeNo, String moneyNo, String statusNo, int page, String search, String modeType, String areaCode, String goodsType, String biddingMethod,String sortMethod,String time,String startTime,String comNo) {
        Map map = new HashMap();
        if (!TextUtils.isEmpty(areaCode))
            map.put("areacode", areaCode);
        if (!TextUtils.isEmpty(cityNo))
            map.put("city", cityNo);
//        map.put("comName", "");
        map.put("limit", 10);
        if (!TextUtils.isEmpty(search))
            map.put("name", search);
        map.put("page", page);
        if (!TextUtils.isEmpty(statusNo))
            map.put("state", statusNo);
        if ("0".equals(typeNo)) {
            typeNo = "";
        }
        map.put("type", typeNo);
        if (!TextUtils.isEmpty(modeType))
//            map.put("modeType", modeType);
            map.put("verticalType", modeType);
        if (!TextUtils.isEmpty(moneyNo))
            map.put("price", moneyNo);
        if (!TextUtils.isEmpty(goodsType))
            map.put("goodsType", goodsType);
        if (!TextUtils.isEmpty(biddingMethod))
            map.put("biddingMethod", biddingMethod);
        if (!TextUtils.isEmpty(time))
            map.put("time", time);
        if (!TextUtils.isEmpty(startTime))
            map.put("startTime", startTime);
        map.put("sortMethod", Integer.valueOf(sortMethod));
        map.put("companyNo",comNo);

        DialogHelper.showProgressDialog2(fragment.getActivity(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().getTenderBidList(map).enqueue(new Callback<BaseEntity<List<TenderListEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<TenderListEntity>>> call, Response<BaseEntity<List<TenderListEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null)
                    return;

                fragment.showList(response.body().getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<List<TenderListEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    /*public void getCityData() {
        APIManager.getInstance().getPickAPI().getAreaSecond(repertory.getAreaCode()).enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setCityDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {

            }
        });
    }*/

    public void getFilterTypeData() {
        DialogHelper.showProgressDialog2(fragment.getActivity(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().tenderNewTypeList().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTypeDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getMoneyTypeData() {
        APIManager.getInstance().getPickAPI().getProjectMoney().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setMoneyDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {

            }
        });
    }

    public void getFilterStatusData() {
        Map map = new HashMap();
        map.put("areacode", repertory.getAreaCode());
        APIManager.getInstance().getPickAPI().getProjectStatus(map).enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {

            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setStatusDatas(data.getData());
                }
            }
        });
    }

    public void getProvinceData() {
        Map map = new HashMap();
        map.put("areaCode", repertory.getAreaCode());
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().getLocationNew(map).enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setProvinceDatas(data.getData());
                }
            }
        });
    }

    public void getCityData(String province, boolean isShowDialog) {
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().getAreaSecond(province).enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setCityDatas(data.getData(), isShowDialog);
                }
            }
        });
    }

    public void getTenderNewTypeList() {
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "数据加载中...", 0, false, null,false);
        APIManager.getInstance().getPickAPI().getTenderNewTypeList().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTenderTypeDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //新增类型过滤接口
    public void getTenderGoodsCategoryAllList(String category) {
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "数据加载中...", 0, false, null,false);
        Map map = new HashMap();
        map.put("type", category);
        APIManager.getInstance().getPickAPI().getTenderGoodsCategoryAllList(map).enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTenderGoodsCategoryAllList(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void findTenderMapPage(String typeNo, String statusNo, String modeType, String goodsType,Double lat, Double log, String distance, String searchName, boolean b,String biddingMethod,String time,String startTime) {
        map = new HashMap();
        page = b ? page + 1 : 1;
        map.put("comName", "");
        map.put("limit", 10);
        map.put("keyword", searchName);
        map.put("page", page);
        if (!"".equals(typeNo) && typeNo != null)
            map.put("type", typeNo);
        if (!"".equals(statusNo) && statusNo != null)
            map.put("state", statusNo);
        if (!"".equals(modeType) && modeType != null)
            map.put("verticalType", modeType);
        if (!TextUtils.isEmpty(goodsType)) {
            map.put("goodsType", goodsType);
        }
        if (!TextUtils.isEmpty(time))
            map.put("time", time);
        if (!TextUtils.isEmpty(startTime))
            map.put("startTime", startTime);
        if (!TextUtils.isEmpty(distance))
        map.put("distance", distance);
        map.put("longitude", log);
        map.put("latitude", lat);
        if (!TextUtils.isEmpty(biddingMethod)){
            map.put("biddingMethod", biddingMethod); // 招标方式 1、公开招标；2、邀请招标
        }
        DialogHelper.showProgressDialog2(fragment.getContext(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().tenderBidderListEsMap(map).enqueue(new ICallBack<BaseEntity<List<TenderListEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<TenderListEntity>> data) {
                if (data == null || data.getState() == null)
                    return;

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showMapList(data.getData(),false,b);
                    fragment.setbiddingListEntityMapList(data.getData(),b,page);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }

            @Override
            public void onFail() {
                super.onFail();
//                fragment.updataView();
            }
        });

    }

    public void getSortTypeData() {
        APIManager.getInstance().getPickAPI().getTenderSortSelect().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setSortDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {

            }
        });
    }

    /**
     * 报名结束（截止）时间
     * */
    public void getPickTimes() {
        if (fragment.getActivity() != null && !fragment.getActivity().isDestroyed() && !fragment.getActivity().isFinishing()){
            DialogHelper.showProgressDialog(fragment.getActivity(), null, "加载中", 0, true, null).setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getPickAPI().getPickTimes().enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setEndTimeData(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getUrlSettingTender(String id) {
        DialogHelper.showProgressDialog2(fragment.getActivity(), null, "加载中", 0, true, null, false);
        APIManager.getInstance().getPickAPI().getUrlSetting("FrontDeskBidding").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id;
                    String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                    String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                    url = url + "&lng=" + lng + "&lat=" + lat;
                    MLog.d("api", "H5跳转链接  " + url);
                    fragment.getUrl(url, id);
                } else {
                    MToast.showToast(fragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    public void findCustomerServiceImAccount(String customerServiceContactsId) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("customerServiceContactsId", customerServiceContactsId);
        APIManager.getInstance().getPickAPI().getfindCustomerServiceImAccount(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    fragment.checkAllowDialog(response.body().getMsg());
                } else {
                    Object data = response.body().getData(); // 接口返回的是String类型
                    String dataIMid = response.body().getData().toString();
                    IMUtils.getInstance().buildSingleTalking(dataIMid);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    public void checkAllowTenderQuestion(String tenderNo,int tenderingType) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("tenderNo", tenderNo);
        APIManager.getInstance().getPickAPI().checkAllowTenderQuestion(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    fragment.checkAllowDialog(response.body().getMsg());
                } else {
                    PickInquireByLetterActivity.start(fragment.getActivity(), tenderNo, "activity",tenderingType);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }


    public void editTender(String tenderNo, int position) {
        Map map = new HashMap();
        map.put("tenderNo", tenderNo);
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().editTender(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.setTvIsGz(position);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void countByBusiness(String businessNo) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("businessNo", businessNo);
        map.put("businessType", 1);
        APIManager.getInstance().getPickAPI().countByBusiness(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if(!"可进行举报监督操作".equals(response.body().getData())){
                        fragment.checkAllowDialog(response.body().getData().toString());
                    }else{
                        ReportActivity.start(fragment.getActivity(), businessNo, "1");
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
    
    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(fragment.getContext(), SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        fragment.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(fragment.getContext(), "登录成功");
                fragment.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(fragment.getContext(), 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    fragment.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(fragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
//        Preferences.saveUserAccount(loginEntity.getImAccount());
//        Preferences.saveUserToken(loginEntity.getImToken());
    }
}
